package top.h1234.web;

import top.h1234.mapper.UserMapper;
import top.h1234.pojo.User;
import top.h1234.service.UserService;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {

    // 获取service对象
    private UserService service = new UserService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 接收用户名和密码
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        // 调用service
        User user = service.login(username, password);

        // 判断是否登录成功
        if (user != null) {
            // 登录成功

            // 判断用户是否勾选了记住我
            String remember = request.getParameter("remember");
            if ("1".equals(remember)) {
                // 勾选了，发送cookie
                // 获取cookie对象
                Cookie c_username = new Cookie("username", username);
                Cookie c_password = new Cookie("password", password);
                // 设置cookie存活时间（7天）
                c_username.setMaxAge(24 * 60 * 60 * 7);
                // 发送cookie
                response.addCookie(c_username);
                response.addCookie(c_password);
            }
            // 存储session
            HttpSession session = request.getSession();
            session.setAttribute("user", user);
            // 查询所有
            request.getRequestDispatcher("/selectAllServlet").forward(request, response);
        } else {
            // 登录失败
            // 存储request域
            request.setAttribute("login_msg", "用户名或密码错误！");
            // 请求转发到login.jsp
            request.getRequestDispatcher("/login.jsp").forward(request, response);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
